<?php
/**
 * @author Jimmy Sole
 * @copyright (c) 2010 Jimmy Sole
 * @version 0.1 alpha
 * This program is free to use and/or modify. Please keep this header intact however. 
 */

// use __autoload() to automagically load classes
function __autoload($class_name)
{
	require_once($class_name . ".php");
}

/**
 * @author Jimmy Sole
 * @package pBlahSession
 */
final class pBlahSession
{
	/**
	 * @var static holds the connection to a database
	 */
	private static $dbh;
	
	/**
	 * Constructor function for pBlahSession class
	 */
	public function __construct()
	{
		try {
			session_start();
		} catch (pBlahException $e) {
			echo $e->getMessage();
		} catch (Exception $e) {
			echo $e->getMessage();
		}
	}
	
	/**
	 * @access public
	 * @return boolean
	 * method to check if the session headers were sent
	 */
	public function isStarted()
	{
		if (headers_sent($file_name, $line_num)) {
			return true;
		} 
	  return false;
	}
	
	/**
	 * @param array $data
	 * @access public
	 * @return string|boolean
	 * method to validate the session
	 */
	public function validateSession(array $data) 
	{
		try {
			// assign $username the first element in the array
			// assign $password the second element in the array
			$username = $data[0];
			$password = $data[1];
			
			// check if the values are empty
			// is so, throw pBlahException (which will return false)
			if ((empty($username)) || (empty($password))) {
				throw new pBlahException("");
			} else {
				// verify against the database's values
				self::$dbh = new pBlahDatabase(Config::HOST, Config::USER, Config::PASS, Config::DBNAME);
				
				if (is_object(self::$dbh)) {
					$query = self::$dbh->query("SELECT id FROM members WHERE username = '" . $_SESSION['username'] . "' AND password = '" . $_SESSION['password'] . "' LIMIT 1");
					
					$fetch = $query->fetch(pBlahDatabase::FETCH_ASSOC);
					
					if (isset($fetch['id'])) {
						$message = "Welcome " . $_SESSION['username'] . "!";
						return $message;
					} else {
						$query = self::$dbh->query("SELECT id FROM admins WHERE username = '" . $_SESSION['username'] . "' AND password = '" . $_SESSION['password'] . "' LIMIT 1");
						
						$fetch = $query->fetch(pBlahDatabase::FETCH_ASSOC);
						
						if (isset($fetch['id'])) {
							$message = "Welcome " . $_SESSION['username'] . "!";
							return $message;
						} else {
							throw new pBlahException("");
						}
					}
				} else {
					throw new pBlahException("");
				}
			}
		} catch (pBlahException $e) {
			return false;
		} catch (Exception $e) {
			return false;
		}
	}
}